import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import dotenv from 'dotenv';
import { createServer } from 'http';

// 导入路由
import authRoutes from './routes/auth';
import gameRoutes from './routes/games';

// 导入中间件
import { errorHandler } from './middleware/errorHandler';
import { notFound } from './middleware/notFound';

// 导入Socket.IO处理器
import { createSocketServer } from './services/socketService';

// 导入Redis配置
import './config/redis';

// 加载环境变量
dotenv.config();

// 创建Express应用
const app = express();
const server = createServer(app);

// 创建Socket.IO服务器
const io = createSocketServer(server);

// 中间件
app.use(helmet()); // 安全头部
app.use(cors({
  origin: process.env.CORS_ORIGIN || 'http://localhost:3000',
  credentials: true
}));
app.use(morgan('combined')); // 日志记录
app.use(express.json()); // 解析JSON
app.use(express.urlencoded({ extended: true })); // 解析URL编码

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/games', gameRoutes);

// 健康检查端点
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'OK', message: 'Server is running' });
});

// 错误处理中间件
app.use(notFound);
app.use(errorHandler);

// 启动服务器
const PORT = process.env.PORT || 3001;
server.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});